<template>
  <div class="container">
    <div class="goods-content bg-color-white pad-l-15 pad-r-15">
      <div class="pad-t-14 pad-b-17">退款商品</div>
      <div>
        <div class="flex pad-r-8">
          <div class="width-79 height-79 img-box"><img v-if="sku.goodsImageUrl" :src="sku.goodsImageUrl" alt="" class="width-79 height-79"></div>
          <div class="flex-item">
            <div class="line-2 mar-l-10">{{sku.goodsTitle}}</div>
            <div class="height-51.5 pad-l-10 pad-r-15 mar-t-6">
              <div v-if="sku.skuDetail" class="font-12 font-color-6 line-1 sku-detail-bar width-200">{{sku.skuDetail}}</div>              
              <div class="flex v-align-c">
                <div class="font-15 flex-item">×{{sku.goodsNum}}</div>
                <div>￥{{sku.goodsPrice}}<span v-if="sku.unit">/{{sku.unit}}</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <div class="flex flex-between font-13 pad-15 mar-t-10 bg-color-white">
        <div>
          <span class="color-red">*</span>
          <span>选择退款方式:</span>
        </div>
        <div class="font-12 font-color-9" @click="showRefundReason = true">
          <div v-if="actionsName">{{actionsName}}</div>
          <div class="flex flex-between" v-else>
            <span>请选择</span>
            <van-icon name="arrow" size="13px" color="#999" />
          </div>
        </div>
      </div>
    </div>
    <div class="bg-color-white line-h-1 mar-t-10">
      <div class="flex flex-between font-13 pad-l-15 pad-r-15 pad-t-15 pad-b-15">
        <div>
          <span class="color-red">*</span>
          <span>退款数量:</span>
        </div>
        <div class="stepper-box">
          <van-stepper :value="goodsCount" min="1" :max="sku.lessGoodsNum" integer @change="onStepChange" input-width="21px" button-size="18px" />
        </div>
      </div>
      <div class="flex flex-between font-13 pad-l-15 pad-r-15 pad-t-15 pad-b-15">
        <div class="v-align-c">
          <!-- <span class="color-red">*</span> -->
          <span class="v-align-c">退款金额(不含运费)<van-icon class="mar-l-2" name="question-o" size="14px" @click="refundExplain" /></span>
        </div>
        <div class="color-red"><span>￥</span><span>{{refundPrice}}</span></div>
      </div>
      <div class="flex flex-between font-13 pad-l-15 pad-r-15 pad-t-10 pad-b-20">
        <div>
          <span class="color-red">*</span>
          <span>退款原因:</span>
        </div>
        <div class="font-12 font-color-9" @click="selRefundReason">
          <div v-if="refundReason">{{refundReason}}</div>
          <div class="flex flex-between" v-else>
            <span>请选择</span>
            <van-icon name="arrow" size="13px" color="#999" />
          </div>
        </div>
      </div>
    </div>
    <div class="mar-t-10">
      <van-cell-group>
        <van-field
          :value="mark"
          clearable
          label="退款说明:"
          placeholder="选填"
          title-width="70px"
          @change="onMarkChange"
        />
      </van-cell-group>
    </div>
    <div class="pad-l-15 pad-r-15 pad-b-15 mar-t-10 bg-color-white upload-bar">
      <div class="pad-t-16 pad-b-16">退款凭证<span class="font-13 font-color-9 mar-l-10">(选填)</span></div>
      <div>
        <div>
          <div v-for="(item, index) in voucherList" :key="index" class="div-list mar-r-9 mar-b-9 pos-rel">
            <div class="delete-icon" @click="deleteVoucher(item.imageId)">
              <!-- <icon class="iconfont icon-shanchu4 font-red font-20"></icon> -->
            </div>
            <div @click="chooseImage">
              <img :src='item.imageUrl' mode="aspectFill" class="width-79 height-79"/>
            </div>
          </div>
        </div>
        <upload-img @upLoadSuccess="upLoadSuccess" @upLoadFail="upLoadFail" @uploadDelete="uploadDelete" :showTip='false'
          :maxLength='maxLength' :count='maxCount' :voucherLength="voucherLength"></upload-img>
      </div>
    </div>
    <div class="height-54"></div>
    <div class="text-align-c submit-footer">
      <button class="submit-btn" @click="cancelOrder">提交</button>
    </div>
    <van-popup
      :show="showSelect"
      round
      position="bottom"
      @close="onClose"
    >
      <van-picker :columns="columns" @change="onChange" @confirm="onConfirm" @cancel="onCancel" show-toolbar />
    </van-popup>
    <van-action-sheet 
      :show="showRefundReason"
      description="选择退款方式"
      :actions="actions"
      @cancel="showRefundReason = false"
      @close="showRefundReason = false"
      @select="onSelectReason"
      cancel-text="关闭"
      :close-on-click-overlay="true"
    />
  </div>
</template>
<script>
import UploadImg from '../components/UploadImg'
import { doRefundOrder, listAfterSaleReason, getRefundDetail } from '@/api/personal'
export default {
  components: { UploadImg },
  data() {
    return {
      mark: '',
      sku: {},
      columns: [],
      refundReason: '',
      refundData: {},
      showSelect: false,
      showRefundReason: false,
      goodsNum: 1,
      actionsName: '',
      maxLength: 3,
      maxCount: 3,
      voucherLength: 0,
      files: [],
      imgFiles: [],
      isUploadFinish: false,
      afterSaleType: '',
      afterSaleReasonId: '',
      voucherList: [],
      isSubmit: false,
      actions: [{
        name: '退货退款',
        id: 10
      }, {
        name: '仅退款',
        id: 20
      }],
      afterSaleTypeMap: {
        10: '退货退款',
        20: '仅退款'
      },
      timer: null,
      afterSaleId: '',
      goodsCount: 1
    }
  },
  computed: {
    refundPrice() {
      console.log('进来吗')
      return Math.round((this.goodsNum * this.sku.goodsPrice) * 100) / 100
    }
  },
  // 监听上传是否完成
  watch: {
    isUploadFinish(val) {
      if (this.isUploadFinish) {
        this.doSave()
      }
    }
  },
  onLoad() {
    // 初始化data
    Object.assign(this.$data, this.$options.data())
  },
  mounted() {
    this.afterSaleId = this.getCurrentPage().query.afterSaleId
    if (this.afterSaleId) {
      // 如果有afterSaleId，说明是从退款失败页面重新申请按钮跳转过来的
      this.showRefundReason = false
      this.getRefundDetail()
    } else {
      this.showRefundReason = true
      this.goodsCount = 1
      this.sku = JSON.parse(this.getCurrentPage().query.sku)
      this.sku.lessGoodsNum = this.sku.goodsNum - this.sku.afterSaleGoodsNum
    }
  },
  onUnload() {
    clearTimeout(this.timer)
    this.timer = null
  },
  methods: {
    getRefundDetail() {
      let params = {
        afterSaleId: this.afterSaleId || '',
        orderId: this.sku.orderId || '',
        goodsId: this.sku.goodsId || '',
        skuId: this.sku.skuId || ''
      }
      this.$pt.showLoading()
      getRefundDetail(params).then(response => {
        if (response.isError) return
        this.$pt.hideLoading()
        this.refundData = response.data
        this.sku = this.refundData.goodsList[0]
        this.goodsCount = this.sku.goodsNum
        this.actionsName = this.afterSaleTypeMap[this.refundData.afterSaleType]
        this.afterSaleType = this.refundData.afterSaleType
        this.mark = this.refundData.customerRemark
        this.goodsNum = this.refundData.goodsNum
        this.files = []
        this.imgFiles = []
        this.voucherList = []
        this.voucherList = this.refundData.imageList || []
        this.voucherLength = this.voucherList.length
        this.refundData.projectOrder.orderGoodsList.forEach(item => {
          if (this.sku.goodsId === item.goodsId) {
            this.sku.lessGoodsNum = item.goodsNum
          }
        })
        this.listAfterSaleReason()
      })
    },
    listAfterSaleReason() {
      this.columns = []
      this.afterSaleReasonId = ''
      this.refundReason = ''
      let params = {
        enterpriseId: this.refundData.enterpriseId || this.sku.enterpriseId
      }
      if (this.afterSaleType === 20) {
        params.refundMoneyFlag = 1
      } else if (this.afterSaleType === 10) {
        params.refundFlag = 1
      }
      listAfterSaleReason(params).then(response => {
        if (response.isError) return
        response.data.forEach(item => {
          if (this.refundData) {
            if (this.refundData.afterSaleReasonId === item.reasonId && item.delFlag === 0) {
              this.refundReason = item.cancelReason
              this.afterSaleReasonId = this.refundData.afterSaleReasonId
            }
          }
          if (item.delFlag === 0) {
            this.columns.push({
              text: item.cancelReason,
              reasonId: item.reasonId
            })
          }
        })
      })
    },
    onClose() {
      // 关闭底部弹窗
    },
    onChange(e) {
      // 选择器变动
    },
    onCancel(e) {
      // 取消选择
      this.showSelect = false
    },
    onConfirm(e) {
      // 确认选择
      console.log('退货原因', e)
      this.refundReason = e.mp.detail.value.text
      this.afterSaleReasonId = e.mp.detail.value.reasonId
      this.showSelect = false
    },
    selRefundReason() {
      // 选择退款原因picker
      if (!this.actionsName) {
        this.$utils.showToast({ title: '请先选择退款方式!' })
        return
      }
      this.showSelect = true
    },
    onSelectReason(action, index) {
      // 退款申请理由选择
      console.log('退款申请理由', action)
      this.actionsName = action.mp.detail.name
      this.afterSaleType = action.mp.detail.id
      this.listAfterSaleReason()
      this.showRefundReason = false
    },
    upLoadSuccess(res) {
      console.log(res)
      this.files = res.files
    },
    upLoadFail(res) {
      console.log(res)
    },
    upLoadComplete() {
      console.log('complete')
    },
    uploadDelete(res) {
      this.files = res.files
    },
    doSave() {
      if (!this.isUploadFinish) {
        // if (this.files.length === 0) return this.$utils.showToast({ title: '请选择要上传的照片' })
        if (this.files.length > 0) {
          this.$utils.showToast({
            title: '图片上传中',
            icon: 'loading',
            duration: 150000,
            mask: true
          })
          // 开始上传文件
          this.doUpload()
        } else {
          this.doRefundOrder()
        }
      } else {
        // 上传完成，清除数据
        this.files = []
        this.doRefundOrder()
      }
    },
    doUpload() {
      const that = this
      let finishCount = 0
      this.files.forEach(file => {
        // 使用微信上传（只能单张上传）
        const uploadTask = that.$pt.uploadFile({
          url: process.env.BASE_API + '/common/uploadFiles',
          filePath: file,
          name: 'files',
          success(res) {
            const result = JSON.parse(res.data)
            if (result.code === 101) {
              that.imgFiles.push(result.data[0])
            } else {
              that.$utils.showToast({ title: '图片上传发生错误:' + result.msg })
              finishCount--
            }
          },
          complete() {
            finishCount++
            if (that.files.length === finishCount) {
              that.isUploadFinish = true
            }
          }
        })
        uploadTask.onProgressUpdate((res) => {
          console.log('上传进度', res.progress)
        })
      })
    },
    deleteVoucher(imageId) {
      let index = this.voucherList.findIndex(item => {
        return item.imageId === imageId
      })
      this.voucherList.splice(index, 1)
      this.voucherLength -= 1
    },
    onMarkChange(e) {
      // 退款说明输入框
      this.mark = e.mp.detail
    },
    onStepChange(e) {
      // 步进器更改
      this.goodsNum = e.mp.detail
    },
    doRefundOrder() {
      if (this.isSubmit) return
      // 退款申请
      let params = {
        customerRemark: this.mark,
        orderId: this.sku.orderId,
        goodsId: this.sku.goodsId,
        skuId: this.sku.skuId || '',
        goodsNum: this.goodsNum,
        afterSaleType: this.afterSaleType,
        afterSaleReasonId: this.afterSaleReasonId,
        refundVoucherList: this.imgFiles
      }
      // 如果有afterSaleId说明是重新申请退款，需要考虑是否有图片
      if (this.afterSaleId) {
        params.refundVoucherList = []
        this.voucherList.forEach(item => {
          params.refundVoucherList.push(item.imageUrl)
        })
        this.imgFiles.forEach(item => {
          params.refundVoucherList.push(item)
        })
        // if (params.refundVoucherList.length > 3) {
        //   params.refundVoucherList = params.refundVoucherList.slice(0, 3)
        // }
      }
      console.log(params)
      doRefundOrder(params).then(response => {
        this.imgFiles = []
        if (response.isError) {
          this.isUploadFinish = false
          return
        }
        this.isUploadFinish = true
        this.isSubmit = true
        this.$utils.showToast({title: '退款申请成功!', mask: true})
        this.$pt.setStorageSync('refundType', true)
        this.timer = setTimeout(() => {
          this.$pt.navigateBack({delta: 1})
        }, 600)
      })
    },
    cancelOrder() {
      // 验证必填项
      if (!this.afterSaleType) return this.$utils.showToast({title: '请选择退款方式!'})
      if (!this.goodsNum || this.goodsNum === 0) return this.$utils.showToast({title: '请填写退款数量!'})
      if (!this.afterSaleReasonId) return this.$utils.showToast({title: '请选择退款原因!'})
      this.$pt.showModal({
        title: '温馨提示',
        content: '确认提交退款申请?',
        success: (res) => {
          if (res.confirm) {
            this.doSave()
          }
        }
      })
    },
    refundExplain() {
      this.$pt.showModal({
        title: '退款金额说明',
        content: '最终退款金额以卖家协商后为准',
        showCancel: false,
        confirmText: '朕知道了'
      })
    }
  }
}
</script>
<style lang="less" scoped>
.container{
  /deep/ .van-cell{
    &::after{
      border-bottom: unset;
    }
  }
  /deep/ .van-picker-column__item--selected{
    font-weight: bold;
  }
}
.sku-detail-bar{
  height: 16px!important;
  line-height: 16px!important;
}
.upload-bar{
  min-height: 140px;
}
.img-box{
  border-radius: 5px;
  overflow: hidden;
  img{
    border-radius: 5px;
  }
}
.line-2{
  max-height: 34px;
  font-size: 13px;
}
.line-h-1{
  line-height: 1;
}
.color-red{
  color: #E60E0E;
}
.sku-block{
  margin-top: 7.5px;
  .sku-row{
    border-radius: 4px;
    background: #F8F8F8;
    .sku-detail{
      .line-1{
        line-height: unset;
      }
    }
  }
}
.upload-style{
  width: 80px;
  height: 80px;
  border: 1px dashed #A9A9A9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  line-height: 1.2;
  color: #ABABAB;
}
.submit-footer{
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 10;
}
.submit-btn{
  width: 100%;  
  height: 54px;
  line-height: 54px;
  text-align: center;
  background: #ffe200;
  color: #333;
  font-size: 16px;
  &::after{
    border: unset;
  }
}
.stepper-box{
  // 步进器左边按钮
  /deep/ .van-stepper__minus {
    // border-radius: 50%;
    background: #EDEDED;
  }
  // 步进器右边按钮
  /deep/ .van-stepper__plus{
    // border-radius: 50%;
    background: #EDEDED;
  }
  // 步进器输入框
  /deep/ .van-stepper__input{
    // background: unset;
    padding: 0;
    // width: 18px;
  }
  /deep/ .van-stepper__minus::after,
  /deep/ .van-stepper__plus::after{
    // width: 2px;
    // height: 10px;
    // background: #999999;
  }
  /deep/ .van-stepper__minus::before,
  /deep/ .van-stepper__plus::before{
    // width: 10px;
    // height: 2px;
    // background: #999999;
  }
}
.div-list {
  float: left;
  display: inline-block;
}

.div-list:last-child {
  border-bottom: none;
}
.icon-del {
  position: absolute;
  top: -10px;
  right: 0px;
  z-index: 10;
}
.delete-icon {
    position: absolute;
    width: 20px;
    height: 20px;
    background: #f43530;
    right: 0;
    top: -10px;
    border-radius: 20px;
    z-index: 5;
  }
  .delete-icon::before {
    content: '';
    width: 13px;
    height: 2px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
  }
</style>
